package com.cooper.security;

import java.security.Key;

import javax.crypto.Cipher;

/**
 * 提供DES加密和解密
 * @Title: DesUtil.java<br>
 * @Date: Dec 15, 2011 11:14:38 PM<br>
 * @Copyright (c) 2011 MiXuan <br> * 
 * @since 1.0
 * @author coraldane
 */
public class Des {
	private static final String DES = "DES";
	private static String strDefaultKey = "MiXuan@Copyright2011";
	
	private String key = strDefaultKey;
	private Cipher encryptCipher = null;
	private Cipher decryptCipher = null;
	
	public Des() throws Exception{
		this(strDefaultKey);
	}
	
	public Des(String strKey) throws Exception{	
		Key key = getKey(strKey.getBytes());
		encryptCipher = Cipher.getInstance(DES);
		encryptCipher.init(Cipher.ENCRYPT_MODE, key);
		decryptCipher = Cipher.getInstance(DES);
		decryptCipher.init(Cipher.DECRYPT_MODE, key);
	}
	
	/**
	 * 从指定字符串生成密钥，密钥所需的字节数组长度为8位
	 * 不足8位时后面补0，超出8位只取前8位
	 * @param arrBTmp 构成该字符串的字节数组
	 * @return 生成的密钥
	 * @throws java.lang.Exception
	 */
	private Key getKey(byte[] arrBTmp) throws Exception {
		//创建一个空的8位字节数组（默认值为0）
		byte[] arrB = new byte[8];
		//将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		//生成密钥
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, DES);
		return key;
	}
	
	public static String byte2Hex(byte[] byteArray) {
        StringBuffer strBuf = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (byteArray[i] >= 0 && byteArray[i] < 16) {
                strBuf.append("0");
            }
            strBuf.append(Integer.toHexString(byteArray[i] & 0xFF));
        }
        return strBuf.toString();
    }
	
	public static byte[] hex2Byte(String hexString) throws Exception {
		byte[] arrB = hexString.getBytes();
		int iLen = arrB.length;
		//两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
	
	public byte[] encrypt(byte[] sourceArray) throws Exception {
		return encryptCipher.doFinal(sourceArray);
	}
	
	public String encode(String source) throws Exception{
		return byte2Hex(encrypt(source.getBytes()));
	}
	
	public byte[] decrypt(byte[] encryptArray) throws Exception {
		return decryptCipher.doFinal(encryptArray);
	}
	
	public String decode(String encrypt) throws Exception{
		return new String(decrypt(hex2Byte(encrypt)));
	}
	
	public static void main(String[] args) throws Exception{
		String text = "admin1987@112";
		String encrypt = new Des().encode(text);
		System.out.println("encrypt text:" + encrypt);
		System.out.println("decrypt text:" + new Des().decode(encrypt));
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
}

